package com.lujianfei.httprequest.retrofit_okhttp;

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.lujianfei.httprequest.R
import com.lujianfei.httprequest.RetrofitManager
import com.lujianfei.httprequest.intercepter.LogIntercepter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*


class RetrofitActivity : AppCompatActivity(), View.OnClickListener {

    val TAG = "RetrofitActivity==";

    @Override
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        findViewById<View>(R.id.btn_get_async).setOnClickListener(this);
        findViewById<View>(R.id.btn_get_sync).setOnClickListener(this);
        findViewById<View>(R.id.btn_post_async).setOnClickListener(this);
        findViewById<View>(R.id.btn_post_sync).setOnClickListener(this);
        findViewById<View>(R.id.btn_intercepter).setOnClickListener(this);
        findViewById<View>(R.id.btn_get_sync_with_manager).setOnClickListener(this);
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.btn_get_async -> {
                getAsync()
            }
            R.id.btn_get_sync -> {
                Thread { getSync() }
            }
            R.id.btn_post_async -> {
                postAsync()
            }
            R.id.btn_post_sync -> {
                Thread { postSync() }
            }
            R.id.btn_intercepter -> {
                postSyncWithIntercepter()
            }
            R.id.btn_get_sync_with_manager -> {
                postSyncWithManager()
            }
        }
    }

    private fun postSyncWithManager() {
        GlobalScope.launch(Dispatchers.Main) {
            val singleJoke = withContext(Dispatchers.IO) {
                RetrofitManager.retrofit.create(OtherApiIinterface::class.java).getSingleJoke("28654780")
            }
            Log.i(TAG,"postSyncWithManager return : $singleJoke")
        }
    }

    private fun getAsync() { // 使用 Retrofit 实现 get 异步请求
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.baidu.com") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build()
        // 创建 网络请求接口 的实例
        val request = retrofit.create(RequestInterface::class.java)
        //对 发送请求 进行封装
        val call = request.getBaidu("大神")
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    Log.d(TAG, "onResponse response :" + response.body()!!.string())
                } catch (e: Exception) {
                    Log.e(TAG, "onResponse e :$e")
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.e(TAG, "onFailure t :$t")
            }
        })
    }

    private fun getSync() { // 使用 Retrofit 实现 get 同步请求
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.baidu.com") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build()
        // 创建 网络请求接口 的实例
        val request = retrofit.create(RequestInterface::class.java)
        //对 发送请求 进行封装
        val call = request.getBaidu("大神")
        try {
            val execute = call.execute()
            Log.d(TAG, "response " + execute.body()!!.string())
        } catch (e: Exception) {
            Log.e(TAG, "" + e)
        }
    }

    private fun postAsync() { // 使用 Retrofit 实现 post 异步请求
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.baidu.com") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build()
        // 创建 网络请求接口 的实例
        val request = retrofit.create(RequestInterface::class.java)
        // 请求参数
        val map: MutableMap<String, Any> = HashMap()
        map["wd"] = "大神"
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        //对 发送请求 进行封装
        val call = request.postBaidu(body)
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    Log.d(TAG, "onResponse response :" + response.body()!!.string())
                } catch (e: Exception) {
                    Log.e(TAG, "onResponse e :$e")
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.e(TAG, "onFailure t :$t")
            }
        })
    }


    private fun postSync() { // 使用 Retrofit 实现 post 同步请求
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.baidu.com") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build()
        // 创建 网络请求接口 的实例
        val request = retrofit.create(RequestInterface::class.java)
        // 请求参数
        val map: MutableMap<String, Any> = HashMap()
        map["wd"] = "大神"
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        //对 发送请求 进行封装
        val call = request.postBaidu(body)
        try {
            val execute = call.execute()
            Log.d(TAG, "response " + execute.body()!!.string())
        } catch (e: Exception) {
            Log.e(TAG, "" + e)
        }
    }

    private fun postSyncWithIntercepter() { // OkhttpClient.Builder 初始化并加入日志拦截神器 LogIntercepter
        val httpClientBuilder = OkHttpClient.Builder()
                .addNetworkInterceptor(LogIntercepter())
        // 使用 Retrofit 实现 post 异步请求
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.baidu.com") //设置网络请求的Url地址
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build()
        // 创建 网络请求接口 的实例
        val request = retrofit.create(RequestInterface::class.java)
        // 请求参数
        val map: MutableMap<String, Any> = HashMap()
        map["wd"] = "大神"
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        //对 发送请求 进行封装
        val call = request.postBaidu(body)
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    Log.d(TAG, "onResponse response :" + response.body()!!.string())
                } catch (e: Exception) {
                    Log.e(TAG, "onResponse e :$e")
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.e(TAG, "onFailure t :$t")
            }
        })
    }
}
